package trading_strategy.strategies;

import org.apache.log4j.Logger;
import trading_strategy.Strategy;
import trading_strategy.events.*;
import trading_strategy.instruments.ListedInstrument;
import trading_strategy.orders.SingleOrderAutomaton;

/**
 * We have a valid signal. If some condition is met, we will trigger an order.
 * This PositionEnterer looks at the flow of trades, and if a certain level ticks, it will hit the order book
 * <p/>
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 24 mai 2010
 * Time: 18:17:46
 * To change this template use File | Settings | File Templates.
 */
public class TriggerPositionEnterer extends PositionTaker {

    // Direction of the trade to execute in order to enter the position

    double triggerPrice;
    double deactivatingPrice;
    long maxTsBeforeExit;

    public static final Logger LOGGER = Logger.getLogger(TriggerPositionEnterer.class);

    public TriggerPositionEnterer(PositionEntererListener strategy, ListedInstrument instrument, Strategy.Direction direction, double triggerPrice, double deactivatingPrice, long maxTsBeforeExit, SingleOrderAutomaton automaton) {
        super(instrument, direction, strategy, automaton);
        this.triggerPrice = triggerPrice;
        this.deactivatingPrice = deactivatingPrice;
        this.maxTsBeforeExit = maxTsBeforeExit;
    }

    @Override
    protected void handleTrade(PublicTradeUpdate ptu) {
        if (ptu.getTs() > maxTsBeforeExit) {
            deactivated(ptu.getTs());
        } else {
            if (direction == Direction.BUY) {
                if (ptu.getPrice() >= triggerPrice) {
                    hit(ptu.getTs());
                } else if (deactivatingPrice > 0 && ptu.getPrice() <= deactivatingPrice) {
                    deactivated(ptu.getTs());
                }
            } else if (direction == Direction.SELL) {
                if (ptu.getPrice() <= triggerPrice) {
                    hit(ptu.getTs());
                } else if (deactivatingPrice > 0 && ptu.getPrice() >= deactivatingPrice) {
                    deactivated(ptu.getTs());
                }
            }
        }
    }

}